import Taro from '@tarojs/taro';
import {handleCityName} from '@/utils/Tools'
import currentEnv from "../../configure/currentEnv";
import { getDispatch } from '../dva';
import { appid_h5, AUTHREDIRECT_ENV, AUTHHOST_ENV, isStandard,appid } from '@/src/config';
import { debounceDelay } from './helper';

//   显示消息框
function toast(str,icon = 'none',delay = 1500){
  Taro.showToast({
    title: str,
    icon,
    duration: delay,
    mask: true
  });
}
function filterTel(tel) {
  let myreg = /^((0|86|17951)?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8})$/;
  if (!myreg.test(tel)) {
    return false;
  }
  return true;
}
function trim(str) {
  return str && str.replace(/\s+/g, '');
}

function isEmail(email) {
  let myreg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
  if (!myreg.test(email)) {
    return false;
  }
  return true;
}

function isPass(pass) {
  let myreg = /^\d{6,20}$/;
  if (!myreg.test(pass)) {
    return false;
  }
  return true;
}

function getLocalUser() {
  return Taro.getStorageSync('user');
}

function isLoginByWechat() {
  let obj = Taro.getStorageSync('user');
  return obj.loginType === 'WECHAT_MINIPROGRAM';
}

function getLocalOpenId() {
  let obj = Taro.getStorageSync('openID');
  return obj;
}

function getToken() {
  let user = getLocalUser();
  if (user.token) {
    return user.token?.accessToken;
  }
  return false;
}

function getMobile() {
  let user = getLocalUser();
  if (user.mobile) {
    return user.mobile;
  }
  return false;
}

function getUserMobile() {
  let user = getLocalUser();
  if (user.userNo) {
    return user.userNo;
  }
  return false;
}

function getSizeByScale(number, designWidth = 750) {
  const sys = Taro.getSystemInfoSync();
  return parseInt((number * sys.screenWidth) / designWidth);
}

function toValidScalePX(o) {
  if (typeof o === 'string') {
    if (/^\d+(\.\d+)?$/.test(o.trim())) {
      return getSizeByScale(parseFloat(o)) + 'px';
    } else {
      return o;
    }
  } else if (typeof o === 'number') {
    return getSizeByScale(o) + 'px';
  }

  return undefined;
}

/**
 *
 * @param {*} param0
 * @param  {...number} rest
 */
function getCalcHeight(o, ...rest) {
  const arr = [];

  let {
    // topMenuHeight = titleHeight + statusBarHeight
    topMenuHeight = false,

    titleHeight = false,
    statusBarHeight = false,

    // bottomMenuHeight = 114 + bottomHight
    bottomHeight = false,
    bottomMenuHeight = false,
  } = {};

  if (typeof o === 'object') {
    ({
      topMenuHeight = false,
      titleHeight = false,
      statusBarHeight = false,
      bottomHeight = false,
      bottomMenuHeight = false,
    } = o);

    arr.push('100vh');
  } else {
    arr.push(toValidScalePX(o));
  }

  if (topMenuHeight) {
    arr.push(`${Taro.$titleHeight + Taro.$statusBarHeight}px`);
  } else {
    if (titleHeight) {
      arr.push(`${Taro.$titleHeight}px`);
    }

    if (statusBarHeight) {
      arr.push(`${Taro.$statusBarHeight}px`);
    }
  }

  if (bottomMenuHeight) {
    arr.push(`${getSizeByScale(114) + Taro.$bottomHight}px`);
  } else {
    if (bottomHeight) {
      arr.push(`${Taro.$bottomHight}px`);
    }
  }

  if (rest?.length) {
    rest.forEach((v) => {
      arr.push(toValidScalePX(v));
    });
  }

  return `calc(${arr.join(' - ')})`;
}

// TODO: 刷新页面失效
function backWithRefreash() {
  let pages = Taro.getCurrentPages();
  let prevPage = pages[pages.length - 2];
  prevPage.setData({ needRefreash: true });
  Taro.navigateBack();
}

function getUrlParam(paramName) {
  let tmp = window.location.search; //"?env=sitShopH5&from=wechat_redirect&code=071cpOFa1CJGWz0qYFFa14NMt52cpOF6&state=1";
  let reg = new RegExp('(^|&)' + paramName + '=([^&]*)(&|$)');
  let r = tmp.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function getAuthUrlByH5(path = '') {
  const redirect_uri =
    AUTHHOST_ENV +
    (path.length > 0 ? path : window.location.hash) +
    '?env=' +
    AUTHREDIRECT_ENV +
    '&from=wechat_redirect';
  const wxauthurl =
    `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid_h5}&redirect_uri=` +
    encodeURIComponent(redirect_uri) +
    '&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
  return wxauthurl;
}

function getOpenId(dispatch, path = '') {
  if (Taro.$isH5) {
    const code = getUrlParam('code');
    let wxauthurl = getAuthUrlByH5(path);
    if (code == null) {
      window.location.href = wxauthurl;
      return;
    } else {
      dispatch({
        type: 'login/getOpenId',
        payload: { loginType: 'WECHAT', username: appid_h5, password: code },
      });
    }
  } else {
    Taro.login({
      success: function (res) {
        if (res.code) {
          dispatch({
            type: 'login/getOpenId',
            payload: { loginType: 'WECHAT', username: appid, password: res.code },
          });
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      },
    });
  }
}

function WXPayByH5(params, paySuccessFunc, payCancelFunc, payFailFunc, orderId = null) {
  function onBridgeReady() {
    let { appId, timeStamp, nonceStr, signType, paySign } = params;
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest',
      {
        appId: appId, //公众号名称，由商户传入
        timeStamp: timeStamp, //时间戳
        nonceStr: nonceStr, //随机串
        package: params.package,
        signType: signType, //微信签名方式：
        paySign: paySign, //微信签名
      },
      (res) => {
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
          if (orderId) {
            //商户买单
            paySuccessFunc(orderId);
          } else {
            paySuccessFunc('支付已完成', 'success');
          }
        } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
          payCancelFunc('支付取消', 'error');
        } else {
          payFailFunc('支付失败', 'error');
        }
      },
    );
  }
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
}

function getLocalLocation() {
  let obj = Taro.getStorageSync('location');
  if (!obj) {
    return null;
  }
  obj = JSON.parse(obj);
  return obj;
}

function getLocalStorage(name) {
  let obj = Taro.getStorageSync(name);
  if (!obj) {
    return null;
  }
  obj = JSON.parse(obj);
  return obj;
}

function setLocalStorage(name, valueObj) {
  Taro.setStorageSync(name, JSON.stringify(valueObj));
}

function getLocalEffectLocation() {
  let localLocation = getLocalLocation();
  let curTimeStamp = new Date().getTime();

  if (localLocation && curTimeStamp - localLocation.timeStamp < 5 * 60 * 1000) {
    return localLocation;
  } else {
    return null;
  }
}

const goGoodDetail = (product, dispatch) => {
  let { id } = product;
  dispatch({
    type: 'productList/setCurProduct',
    payload: { ...product },
  });
  Taro.navigateTo({
    url:`/mainSubPack/goodsDetail/index?id=${id}`
  })
};

const goProductDetail = (product) => {
  let { id } = product;
  const dispatch = getDispatch();

  dispatch({
    type: 'productList/setCurProduct',
    payload: { ...product },
  });

  Taro.navigateTo({
    url:`/mainSubPack/goodsDetail/index?id=${id}`
  })
};

const goProductDetailById = (productReleaseId) => {
  const dispatch = getDispatch();

  dispatch({
    type: 'productList/setCurProduct',
    payload: undefined,
  });

  let url = '/mainSubPack/goodsDetail/index' + '?' + 'id=' + productReleaseId;
  Taro.navigateTo({
    url,
  });
};

const getHomePagePath = () => {
  let url = '/pages/mainPages/homePage/homePage';
  if (isStandard) {
    url = '/pages/mainPages/tabsPage/index';
  }
  return url;
};

const goHomePage = (dispatch, type = '') => {
  let url = getHomePagePath();
  if (type == 'switchTab' && url.indexOf('homePage') > 0) {
    Taro.switchTab({ url });
  } else {
    dispatch &&
      dispatch({
        type: 'otherApi/setTabsPageName',
        payload: 'homePage',
      });
    Taro.reLaunch({ url });
  }
};

const getCartPagePath = () => {
  let url = '/pages/mainPages/cart/index';
  if (isStandard) {
    url = '/pages/mainPages/tabsPage/index?tabName=cart';
  }
  return url;
};

const goCartPage = (dispatch, type = '') => {
  let url = getCartPagePath();
  if (type == 'switchTab' && url.indexOf('cart') > 0) {
    Taro.switchTab({ url });
  } else {
    dispatch({
      type: 'otherApi/setTabsPageName',
      payload: 'cart',
    });
    Taro.reLaunch({ url });
  }
};

const goMePage = (dispatch) => {
  let url = '/pages/mainPages/me/index';
  if (isStandard) {
    url = '/pages/mainPages/tabsPage/index';
    dispatch({
      type: 'otherApi/setTabsPageName',
      payload: 'me',
    });
  }
  Taro.reLaunch({ url });
};

const wechatUserInfo = {
  set: (v) => {
    Taro.setStorageSync('wechatUserInfo', v);
  },
  get: () => {
    let obj = Taro.getStorageSync('wechatUserInfo');
    return obj;
  },
};

const setTitle = (title = '') => {
  if (Taro.$platform === 'windows') {
    return;
  }

  Taro.setNavigationBarTitle({
    title: title,
  });
  // if (Taro.$isH5) {
  //   let dom = document.createElement('iframe');
  //   dom.setAttribute('src', 'https://www.baidu.com/favicon.ico');
  //   dom.setAttribute('height', '0px');
  //   dom.onload = function () {
  //     setTimeout(function () {
  //       document.body.removeChild(dom);
  //     }, 5);
  //   };
  //   document.body.appendChild(dom);
  // }
};

const getDotStr = (num = 0) => {
  let str = parseFloat(num).toFixed(2).toString();
  let strArr = str.split('.');
  return '.' + strArr[1];
};

const getFont = () => {
  return new Promise((resolve, reject) => {
    Taro.loadFontFace({
      global: true,
      family: 'DINfont',
      source: 'url("https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/weapp/DIN-Alternate-Bold.ttf")',
      success: () => {
        console.log('load DIN Alternate Bold success');
        resolve();
      },
      fail: () => {
        console.log('load DIN Alternate Bold fail');
        reject();
      },
    });
  });
};

const getDirectionalCoupons = () => {
  const dispatch = getDispatch();
  const token = getToken();
  if (token) {
    dispatch({
      type: 'otherApi/checkTokenModel',
      payload: { token },
    }).then((res) => {
      if (res?.valid == 1) {
        dispatch({ type: 'giftCard/getDirectionalCouponList' });
      }
    });
  }
};

function getParames(sUrl,sKey){
  var sHref = sUrl || location.href;
  var args = sHref.split('?');
  if (args[0] === sHref) {
      return '';
  }
  var hrefarr = args[1].split('#')[0].split('&');
  var obj = {};
  for (var i = 0; i < hrefarr.length; i++) {
      hrefarr[i] = hrefarr[i].split('=');
      obj[hrefarr[i][0]] = hrefarr[i][1];
  }
  if (!sKey) {
      return obj;
  } else {
      return obj[sKey] || '';
  }
}
/*
 * date [number] 时间戳或者时间标准
 * fmt [string] 时间格式
 */
function format(date, fmt = 'YYYY-MM-DD') {

	let newDate = date;
	let fmts = fmt;

	//fmts='YYYY-MM-DD HH:mm:ss'
	if (!newDate) {
		newDate = new Date;
	}
	if (typeof newDate === 'number') {
		newDate = new Date(newDate);
	}
	const o = {
		'M+': newDate.getMonth() + 1,
		'D+': newDate.getDate(),
		'h+': newDate.getHours() % 12 === 0 ? 12 : newDate.getHours() % 12,
		'H+': newDate.getHours(),
		'm+': newDate.getMinutes(),
		's+': newDate.getSeconds(),
		'q+': Math.floor((newDate.getMonth() + 3) / 3),
		S: newDate.getMilliseconds(),
	};
	const week = {
		0: '\u65e5',
		1: '\u4e00',
		2: '\u4e8c',
		3: '\u4e09',
		4: '\u56db',
		5: '\u4e94',
		6: '\u516d',
	};
	if (/(Y+)/.test(fmts)) {
		fmts = fmts.replace(RegExp.$1, (`${newDate.getFullYear()}`).substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmts)) {
		fmts = fmts.replace(RegExp.$1, () => {
			if (RegExp.$1.length > 1) {
				if (RegExp.$1.length > 2) {
					return `\u661f\u671f${week[newDate.getDay()]}`;
				}
				return `\u5468${week[newDate.getDay()]}`;
			}
			return week[`${newDate.getDay()}`];
		});
	}
	Object.keys(o).forEach((k) => {
		if (new RegExp(`(${k})`).test(fmts)) {
			fmts = fmts.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length)));
		}
	});
	return fmts;
};

function handleUpdateLoca(data){
  Taro.setStorageSync('position',{...data})
  Taro.setStorageSync('cityInfo',{...data})
  Taro.eventCenter.trigger('updateLocation')
  if(currentEnv.project != 'yingjing' && !Taro.getStorageSync('selectMerchant')?.id){
    Taro.navigateTo({
      url:'/mainPages/select-cinema/index'
    })
  }
}
const handleGetLocation = debounceDelay(()=>{
  if(process.env.TARO_ENV == 'h5'){
    handleCityName()
  }else{
    Taro.getLocation({
      type: 'wgs84',
      success: (res) => {
        let data = {
          latitude:res.latitude,
          longitude:res.longitude,
          city:'全国',
          cityCode:'0',
          name:'全国'
        }
        if(res.latitude == Taro.getStorageSync('position')?.latitude && res.longitude == Taro.getStorageSync('position')?.longitude) return;
        Taro.$get('/common/external/tianDiTu/city',{
          latitude:res.latitude,
          longitude:res.longitude,
        }).then(ret=>{
          if(ret.code == '1'){
            Object.assign(data,{
              city:ret.content.name,
              name:ret.content.name,
              cityCode:ret.content.code,
              timeStamp:Date.now()
            })
            if(!Taro.getStorageSync('position').city){
              handleUpdateLoca(data)
              return;
            }else{
              if(data.city != Taro.getStorageSync('cityInfo').name){
                Taro.showModal({
                  title:`定位到您在${data.city},是否切换?`,
                  confirmText:'切换',
                  confirmColor:'#F86720',
                  success: (ret) => {
                    if (ret.confirm) {
                      handleUpdateLoca(data)
                    }
                  }
                })
                return;
              }
              handleUpdateLoca(data);
            }
          }
        })
      },
      template:err=>{
        console.log(err)
      }
    })
  }
},3000)

export {
  filterTel,
  trim,
  isEmail,
  isPass,
  getLocalUser,
  getToken,
  getMobile,
  getUserMobile,
  getSizeByScale,
  toValidScalePX,
  getCalcHeight,
  backWithRefreash,
  getUrlParam,
  getOpenId,
  WXPayByH5,
  getAuthUrlByH5,
  getLocalOpenId,
  getLocalEffectLocation,
  setLocalStorage,
  isLoginByWechat,
  getLocalStorage,
  goGoodDetail,
  getHomePagePath,
  goHomePage,
  getCartPagePath,
  goCartPage,
  goMePage,
  setTitle,
  getDotStr,
  wechatUserInfo,
  goProductDetail,
  goProductDetailById,
  getFont,
  getDirectionalCoupons,
  getParames,toast,format,handleGetLocation
};

export default {
  filterTel,
  trim,
  isEmail,
  isPass,
  getLocalUser,
  getToken,
  getMobile,
  getUserMobile,
  getSizeByScale,
  toValidScalePX,
  getCalcHeight,
  backWithRefreash,
  getUrlParam,
  getOpenId,
  WXPayByH5,
  getAuthUrlByH5,
  getLocalOpenId,
  getLocalEffectLocation,
  setLocalStorage,
  isLoginByWechat,
  getLocalStorage,
  goGoodDetail,
  getHomePagePath,
  goHomePage,
  getCartPagePath,
  goCartPage,
  goMePage,
  setTitle,
  getDotStr,
  wechatUserInfo,
  goProductDetail,
  goProductDetailById,
  getFont,
  getDirectionalCoupons,
  getParames,
  handleGetLocation
};
